<template>
    <div>
        <a-modal v-model:visible="modalVisible" title="变更计费方式" @ok="handleOk" :confirm-loading="confirmLoading">
            <div>
                <a-form :model="form">
                    <a-form-item label="实例ID">
                        {{ instance?.Instance?.instanceId }}
                    </a-form-item>
                    <a-form-item label="实例名称">
                        {{ instance?.Instance?.name }}
                    </a-form-item>
                    <a-form-item label="当前计费模式">
                        {{ payType[instance?.Instance?.skuName] }} ￥ {{ instance_price }}/{{
                            unitType[instance?.Instance?.skuName] }}
                    </a-form-item>
                    <a-form-item label="变更计费方式">
                        <div v-if="['card_less', 'free', 'payg'].includes(instance?.Instance?.skuName)">包月包周包天</div>
                        <div v-if="['daily', 'weekly', 'monthly'].includes(instance?.Instance?.skuName)">按量付费</div>
                    </a-form-item>

                    <a-form-item label="" v-if="['card_less', 'free', 'payg'].includes(instance?.Instance?.skuName)">
                        <a-radio-group v-model:value="form.skuName">
                            <a-radio value="daily">包天</a-radio>
                            <a-radio value="weekly">包周</a-radio>
                            <a-radio value="monthly">包月</a-radio>
                        </a-radio-group>
                    </a-form-item>

                    <div class="flex cost-calculation">
                        <div v-if="['daily', 'weekly', 'monthly'].includes(form.skuName)">
                            <a-input-number id="inputNumber" v-if="form.skuName == 'monthly'" v-model:value="form.duration"
                                :max="12" />
                            <span style="margin-left:8px;" v-if="form.skuName == 'monthly'">月</span>
                            <a-input-number id="inputNumber" v-if="form.skuName == 'daily'" v-model:value="form.duration"
                                :max="100" />
                            <span style="margin-left:8px;" v-if="form.skuName == 'daily'">日</span>
                            <a-input-number id="inputNumber" v-if="form.skuName == 'weekly'" v-model:value="form.duration"
                                :max="100" />
                            <span style="margin-left:8px;" v-if="form.skuName == 'weekly'">周</span>
                        </div>

                        <div style="margin-left: auto;" class="instance-modal">
                            <div>存储费用<span class="col-money">￥ {{ formatInstanceOpenFee }}</span></div>
                            <div>实例费用<span class="col-money">￥ {{ formatInstanceFee() }}</span></div>
                            <div>代金券抵扣<span class="col-money">￥ {{ formatTicket() }}</span></div>
                            <div>折扣<span class="col-money">{{ (accountInfo?.userDiscount?.instanceDiscount) * 100 || 0
                            }}折</span></div>
                            <div>应付金额<span class="col-money">￥ {{ totalPrice }}</span></div>
                            <div>账户可用余额<span class="col-money">￥ {{ accountInfo.balance }}</span></div>
                            <div v-if="['daily', 'weekly', 'monthly'].includes(form.skuName)">自动续费<a-switch class="ml-8"
                                    v-model:checked="form.autoRenew"
                                    :disabled="(accountInfo.balance < totalPrice * 2)"></a-switch>
                            </div>
                            <div class="fz-12 col-8A93A7">余额足够时，到期自动续费</div>
                        </div>

                    </div>
                </a-form>
            </div>
        </a-modal>
    </div>
</template>

<script setup>
import { defineProps, defineEmits, computed, ref } from 'vue';
import { handleInstance } from 'api/modules/api.instance'
import { storeToRefs } from 'pinia'
import userInfoStore from '@/stores/userInfo.js'
import { XsyMessage } from '@/libs/util.toast'
import { printGBSize } from '@/libs/util.common'
const useUserInfoStore = userInfoStore()
const { accountInfo } = storeToRefs(useUserInfoStore);


const props = defineProps({
    modelValue: {
        type: Boolean,
    },
    instance: {
        type: Object,
        default: {}
    }
});

const payType = {
    'card_less': '按量付费',
    'free': '按量付费',
    'payg': '按量付费',
    'bidding': '竞价实例',
    'daily': '包天',
    'weekly': '包周',
    'monthly': '包月',
}

const form = ref({
    duration: 1
})

if (['daily', 'weekly', 'monthly'].includes(props.instance?.Instance?.skuName)) {
    form.value.skuName = 'payg'
} else {
    form.value.skuName = 'daily'
}

const emit = defineEmits(['update:modelValue', 'handelOpt', 'handelNoBalance']);
const modalVisible = computed({
    get: () => props.modelValue,
    set: v => emit('update:modelValue', v),
});


// 确定按钮的回调
const confirmLoading = ref(false)
const handleOk = () => {
    if (!form.value.skuName) {
        XsyMessage.error("请选择变更方式");
        return
    }

    const params = {
        instanceId: props.instance?.Instance?.instanceId,
        method: 'setting',
        subject: 'change_pay_type',
        changeToType: form.value.skuName,
        duration: form.value.duration,
        autoRenew: form.value.autoRenew ? 1 : 0
    }
    confirmLoading.value = true
    handleInstance(params).then((res) => {
        confirmLoading.value = false
        if (res.code == 0) {
            emit('update:modelValue', false)
            emit('handelOpt', props.instance?.Instance?.instanceId)
        }
    }).catch(err => {
        confirmLoading.value = false
        if (err.code == 10111) {
            emit('update:modelValue', false)
            emit('handelNoBalance', totalPriceFee.value)
        }
    })
};

// 获取实例单价
const instance_price = ref('')
const getInstancePrice = () => {
    instance_price.value = props.instance?.Order?.price
}

getInstancePrice()

// 存储费用
const formatStorageTotalFee = ref(0)
const formatInstanceOpenFee = computed(() => {
    const price = accountInfo?.value?.runningInstanceStoragePrice || 0
    const discount = accountInfo.value?.userDiscount?.instanceDiscount || 1
    const storageNum = printGBSize(props.instance?.InstancePhysicalState?.systemDiskSize + props.instance?.InstancePhysicalState?.dataDiskSize)
    let duration = 0

    if (form.value.skuName == 'daily') {
        duration = 1 * 24 * form.value.duration
    } else if (form.value.skuName == 'weekly') {
        duration = 1 * 24 * 7 * form.value.duration
    } else if (form.value.skuName == 'monthly') {
        duration = 1 * 24 * 30 * form.value.duration
    } else {
        duration = 1
    }

    const countFee = price * storageNum * duration * discount
    formatStorageTotalFee.value = countFee.toFixed(2) || 0
    return countFee.toFixed(2) || 0
})

// 实例费用  实例价格 * 用户折扣
const formatInstanceFee = () => {
    let price = ''
    const discount = accountInfo.value?.userDiscount?.instanceDiscount || 1
    const gpuNum = props.instance?.Instance?.gpuNum
    const filterItem = props.instance?.MachineSku.find(item => {
        return item.skuName == form.value.skuName
    })

    price = parseFloat((filterItem?.price * form.value.duration * gpuNum * discount).toFixed(2))

    return price || 0
}

// 代金券抵扣
const formatTicket = () => {
    const voucherFee = props.instance?.Instance?.payByVoucher == 1 ? accountInfo?.value?.userTicket?.amount : 0
    const instanceFee = formatInstanceFee()
    const countFee = (parseFloat(instanceFee) + parseFloat(formatStorageTotalFee.value)) < parseFloat(voucherFee) ? (parseFloat(instanceFee) + parseFloat(formatStorageTotalFee.value)) : parseFloat(voucherFee)
    return countFee.toFixed(2) || 0
}

// 计算费用  实例价格 * 用户折扣 + 存储费用 - 代金券金额
const totalPriceFee = ref('')
const totalPrice = computed(() => {
    let price = ''
    const discount = accountInfo.value?.userDiscount?.instanceDiscount || 1
    const voucherFee = props.instance?.Instance?.payByVoucher == 1 ? accountInfo?.value?.userTicket?.amount : 0
    const gpuNum = props.instance?.Instance?.gpuNum

    const filterItem = props.instance?.MachineSku.find(item => {
        return item.skuName == form.value.skuName
    })


    price = (Number(formatStorageTotalFee.value) + parseFloat((filterItem?.price * form.value.duration * gpuNum * discount).toFixed(2)) - parseFloat(voucherFee)) < 0 ? 0 : Number(formatStorageTotalFee.value) + parseFloat((filterItem?.price * form.value.duration * gpuNum * discount).toFixed(2)) - parseFloat(voucherFee)
    totalPriceFee.value = price.toFixed(2) || 0
    return price.toFixed(2) || 0
})

const unitType = {
    'card_less': '小时',
    'free': '小时',
    'payg': '小时',
    'bidding': '小时',
    'daily': '天',
    'weekly': '周',
    'monthly': '月',
}

</script>

<style scoped lang="less">
.instance-modal {
    font-size: 14px;
    color: #646F87;
}
</style>
